﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;
using Board1.Info;
using System.Windows.Media;
using System.Threading;
using ImageTools.IO.Gif;
namespace Board1.UIPage
{
    public partial class MediaPlayer : PhoneApplicationPage
    {
        const string PLAYING = "/ButtonIcon/play_black.png";
        const string NOTPLAYING = "";
        private ObservableCollection<ZingSong> playlistItem = new ObservableCollection<ZingSong>();
        private int index = 0, lastindex = 0;
        private List<string> playListLink;
        private List<Uri> uriList = new List<Uri>();
        public MediaPlayer()
        {
            // khoi tao playlist, play bai hat dau tien
            InitializeComponent();
            ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
            playListLink = ListResultSong.linkMP3;
            for (int i = 0; i < playListLink.Count; i++)
            {
                Uri temp = new Uri(playListLink[i], UriKind.Absolute);
                uriList.Add(temp);
            }
            playerElement.Source = uriList[0];
            playlistItem = ListResultSong.selectedList;
            playlistItem[index].stateImg = PLAYING;
            playlist.ItemsSource = playlistItem;
            playerElement.CurrentStateChanged += new RoutedEventHandler(song_CurrentStateChanged);

        }

        //bat su kien khi noi dung media dang choi co thay doi trang thai
        private void song_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            string text = playerElement.CurrentState.ToString();
            Console.WriteLine(text);
            if (playerElement.CurrentState == MediaElementState.Playing)
            {
                Duration = playerElement.NaturalDuration.TimeSpan.TotalSeconds;
                totalSec.Text = " | " + (Convert.ToInt16(Duration) / 60).ToString() + ":" + (Convert.ToInt16(Duration) % 60).ToString();
                ThreadPool.QueueUserWorkItem(o =>
                    {
                        while (true)
                        {
                            Dispatcher.BeginInvoke(new Action(() => progressBar.Value = playerElement.Position.TotalSeconds * 100 / Duration));
                            Thread.Sleep(10);
                        }
                    }
                    );
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            playerElement.AutoPlay = true;
            playerElement.Play();
        }

        // click vao button Previous
        private void previousButtClick(object sender, EventArgs e)
        {
            PreviousSong();
            playlist.ScrollIntoView(playlist.Items[index]);
        }

        // click vao button Play
        private void playButtClick(object sender, EventArgs e)
        {
            playerElement.Play();
        }

        // click vao button Pause
        private void pauseButtClick(object sender, EventArgs e)
        {
            playerElement.Pause();
        }

        //click vao button Next
        private void nextButtClick(object sender, EventArgs e)
        {
            NextSong();
            if (index != -1)
                playlist.ScrollIntoView(playlist.Items[index]);
        }

        //khi click vao 1 item tren playlist
        private void OnClickPlaylistItem(object sender, SelectionChangedEventArgs e)
        {
            lastindex = index;
            //playlistItem[index].stateImg = NOTPLAYING;
            if(playlist.ItemsSource!=null)
            index = this.playlist.SelectedIndex;
            //playlistItem[this.playlist.SelectedIndex].stateImg = PLAYING;
            if (index != -1 & lastindex != -1)
            {
                playlistItem[lastindex].stateImg = NOTPLAYING;
                playlistItem[index].stateImg = PLAYING;
                playlist.ItemsSource = null;
                playlist.ItemsSource = playlistItem;
                playerElement.Stop();
                playerElement.Source = uriList[index];
                playerElement.Play();
            }
        }

        // Next sang bai ke tiep
        private void NextSong()
        {
            lastindex = index;
            index = (index + 1) % uriList.Count();
            if (index != -1 && lastindex != -1)
            {
                playlistItem[lastindex].stateImg = NOTPLAYING;
                playlistItem[index].stateImg = PLAYING;
                playlist.ItemsSource = null;
                playlist.ItemsSource = playlistItem;
                playerElement.Stop();
                playerElement.Source = uriList[index];
                playerElement.Play();
            }
        }

        // Previous sang bai hat truoc day
        private void PreviousSong()
        {
            lastindex = index;
            if (index != 0)
                index = (index - 1) % uriList.Count();
            else
                index = uriList.Count() - 1;
            if (index != -1 && lastindex != -1)
            {
                playlistItem[index].stateImg = PLAYING;
                playlistItem[lastindex].stateImg = NOTPLAYING;
                playlist.ItemsSource = null;
                playlist.ItemsSource = playlistItem;
                playerElement.Stop();
                playerElement.Source = uriList[index];
                playerElement.Play();
            }
        }

        public double Duration { set; get; }

        // Bat su kien khi ket thuc bai hat, chon Next sang bai tiep theo
        private void OnMediaEnded(object sender, RoutedEventArgs e)
        {
            NextSong();
            if (index != -1)
                playlist.ScrollIntoView(playlist.Items[index]);
        }

        // Bat su kien khi gia tri progress bar thay doi
        private void OnProgressValueChange(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            currentSec.Text = (Convert.ToInt16(playerElement.Position.TotalSeconds) / 60).ToString() + ":" +
                (Convert.ToInt16(playerElement.Position.TotalSeconds) % 60).ToString();
        }
    }
}